

window.$ = window.Zepto;
// 打包时用type1

var car = {};

car.carImg = "images/games/car2.png";

car.init = function() {

	car.canvas = document.getElementById("gameCanvas");
	if (car.canvas && car.canvas.getContext) {
		car.ctx = car.canvas.getContext("2d");
		if (!car.ctx) {
			return false;
		}
	}
	car.canvas2 = document.getElementById("cloudCanvas");
	if (car.canvas2 && car.canvas2.getContext) {
		car.ctx2 = car.canvas2.getContext("2d");
		if (!car.ctx2) {
			return false;
		}
	}
	
	// 设置默认值，初始里程数，舞台宽与高，进度，速度
	car.mileage = 0;
	car.scale = 0.6;
	car.width = 681;
	car.height = 384;
	car.progress = 0;
	car.roadWidth = 420 * car.scale;
	car.defaultDpeed = 15;
	car.jsdSpeed = 20;
	car.x = 430 * car.scale;
	car.rotation = 0;
	car.currentSpeed = 0;
	car.useSpeed = car.defaultDpeed;
	car.roadX = [ 430, 430, 430, 430, 425, 417, 408, 398, 393, 390, 391, 395, 403, 419, 437, 462, 493, 525, 559, 590, 618, 641, 658, 670, 677, 679, 679, 681, 680, 677, 675, 674, 673, 673, 671, 666, 660, 649, 636, 620, 599, 576, 550, 524, 498, 476, 457, 445, 437, 431, 430, 430, 430, 430, 430, 430, 430, 430, 430, 430, 432, 437, 445, 460, 479, 504, 530, 555, 580, 600, 615, 624, 627, 627, 624, 619, 615, 605, 597, 586, 576, 566, 552, 540, 528, 514, 503, 492, 479, 469, 459, 451, 446, 439, 437, 437, 438, 444, 451, 461, 471, 482, 495, 508, 522, 534, 544, 552, 560, 564, 566, 565, 561, 559, 556, 552, 548, 545, 540, 535, 528, 523, 518, 510, 504, 497, 490, 483, 478, 469, 463, 456, 450, 445, 440, 435, 431, 430, 430, 430, 430, 430, 430, 430];
	car.dieX = [ -1 , -1, -1, 1024, 977, 951, 951, 951, 951, 951, 976, 1000, 1015, 1040, -1, -1, -1, 100, 150, 175, 200, 200, 210, 220, 230, 230, 230, 230, 192, 150, 111, 100, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 771, 734, 713, 713, 737, 755, 771, 771, 771, 771, 771, 771, 790, 808, 850, 890, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 114, 150, 184, 184, 184, 230, 240, 240, 240, 240, 230, 180, 150, 130, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1024, 1024, 1051, 1051, 1024, 1000, 1000, 980, 964, 945, 945, 945, 955, 980, 1024, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1];
	car.roadX.reverse();
	car.dieX.reverse();
	car.score = 100;
	car.chaosRotation = 0;
	car.lightOn = true;
	car.kmAlpha = 0;
	car.addedLocal = false;
	car.start = false;
	car.flyY = 0;
	car.debug = false;
	car.flash = false;
	car.flashOn = false;
	car.carAlpha = 1;
	car.hpX = 80 * car.scale;

	// 加载赛道(由于ios限制，赛道截成8段)
	car.road1 = new Image();
	car.road1.src = "images/games/road1.jpg";
	car.road1.onload = car.checkComplete;

	car.road2 = new Image();
	car.road2.src = "images/games/road2.jpg";
	car.road2.onload = car.checkComplete;

	car.road3 = new Image();
	car.road3.src = "images/games/road3.jpg";
	car.road3.onload = car.checkComplete;

	car.road4 = new Image();
	car.road4.src = "images/games/road4.jpg";
	car.road4.onload = car.checkComplete;

	car.road5 = new Image();
	car.road5.src = "images/games/road5.jpg";
	car.road5.onload = car.checkComplete;

	car.road6 = new Image();
	car.road6.src = "images/games/road6.jpg";
	car.road6.onload = car.checkComplete;

	car.road7 = new Image();
	car.road7.src = "images/games/road7.jpg";
	car.road7.onload = car.checkComplete;

	car.road8 = new Image();
	car.road8.src = "images/games/road8.jpg";
	car.road8.onload = car.checkComplete;

	// 加载车子
	car.theCar = new Image();
	car.theCar.src = car.carImg;
	car.theCar.onload = car.checkComplete;

	// 加载车印子
	car.theCarShadow = new Image();
	car.theCarShadow.src = "images/games/carShadow.png";
	car.theCarShadow.onload = car.checkComplete;

	// 加载淤泥
	car.oilArr = new Array();
	car.oilArr[0] = new Image();
	car.oilArr[0].src = "images/games/oil_1.png";
	car.oilArr[0].onload = car.checkComplete;

	car.oilArr[1] = new Image();
	car.oilArr[1].src = "images/games/oil_2.png";
	car.oilArr[1].onload = car.checkComplete;

	// 加载金嘉护
	car.jjh = new Array();
	car.jjh[0] = new Image();
	car.jjh[0].src = "images/games/t1.png";
	car.jjh[0].onload = car.checkComplete;

	car.jjh[1] = new Image();
	car.jjh[1].src = "images/games/t2.png";
	car.jjh[1].onload = car.checkComplete;

	car.jjh[2] = new Image();
	car.jjh[2].src = "images/games/t3.png";
	car.jjh[2].onload = car.checkComplete;

	car.jjh[3] = new Image();
	car.jjh[3].src = "images/games/t4.png";
	car.jjh[3].onload = car.checkComplete;

	car.jjh[4] = new Image();
	car.jjh[4].src = "images/games/t5.png";
	car.jjh[4].onload = car.checkComplete;

	car.jjh[5] = new Image();
	car.jjh[5].src = "images/games/t6.png";
	car.jjh[5].onload = car.checkComplete;

	car.jjh[6] = new Image();
	car.jjh[6].src = "images/games/t7.png";
	car.jjh[6].onload = car.checkComplete;

	car.jjhRandom = 0;

	// 加载米数底板
	car.eachkmImg = new Image();
	car.eachkmImg.src = "images/games/eachKM.png";
	car.eachkmImg.onload = car.checkComplete;

	// 加载车的光圈
	car.light = new Image();
	car.light.src = "images/games/carLight.png";
	car.light.onload = car.checkComplete;

	// 加载生命条槽
	car.hpbg = new Image();
	car.hpbg.src = "images/games/hpbg.png";
	car.hpbg.onload = car.checkComplete;

	// 加载生命条
	car.hp = new Image();
	car.hp.src = "images/games/hp.png";
	car.hp.onload = car.checkComplete;

	// 加载云朵
	car.cloud = new Array();
	car.cloud[0] = new Image();
	car.cloud[0].src = "images/games/c1.png";
	car.cloud[0].onload = car.checkComplete;

	car.cloud[1] = new Image();
	car.cloud[1].src = "images/games/c2.png";
	car.cloud[1].onload = car.checkComplete;

	car.cloud[2] = new Image();
	car.cloud[2].src = "images/games/c3.png";
	car.cloud[2].onload = car.checkComplete;

	car.cloud[3] = new Image();
	car.cloud[3].src = "images/games/c4.png";
	car.cloud[3].onload = car.checkComplete;

	car.setSize();
}

// 设置画布的宽高
car.setSize = function() {
	var _w = $.bodyWidth(), _h = $.bodyHeight();
	$("#gameCanvas, #cloudCanvas").css({"height": _h + "px", "width": _h * 1.78 + "px", "marginLeft": (-_h * 1.78) / 2 + "px"});
	if (_w / _h > 1.65) {
		car.hpX = 80 * car.scale;
	} else {
		car.hpX = 140 * car.scale;
	}
}

// 判断内容加载是否完成
car.checkComplete = function() {
	car.progress += 1;
	if (car.progress == 23) {
		$("#gameing .start .btn").on("click", car.onStartClick);
		$("#endPop a").on("click", car.onReplayClick);
		$("#startPop").css({"-webkit-transition": "all 0.1s ease-out"});
		window.addEventListener("deviceorientation", car.devicemotionHandler, false);
		document.onkeydown = car.keyDown;
		car.run();
	}
}

car.onStartClick = function(e) {
	if ($.pageAnimating() || $.touchMoved) { return false;}
	if (!car.startClicked) {
		car.setSize();
		car.startClicked = true;
		page.bgAudio(null);
		page.sound("audio/doo.mp3");
		$("#gameing .start .btn").attr("class", "btn ready3");
		setTimeout(function(){
			page.sound("audio/doo.mp3");
			$("#gameing .start .btn").attr("class", "btn ready2");
			setTimeout(function(){
				page.sound("audio/doo.mp3");
				$("#gameing .start .btn").attr("class", "btn ready1");
				setTimeout(function(){
					$("#gameing .start .btn").addClass("hide");
					$("#gameing .start").hide();
					car.start = true;
					car.run();
					page.bgAudio("audio/runing.mp3");
				},1000);
			},1000);
		},1000);
	}
	return false;
}

car.onReplayClick = function(e) {
	car.setSize();
	car.theCar = new Image();
	car.theCar.src = car.carImg;
	$("#endPop").addClass("hide");
	$("#gameing").show().find(".start .btn").attr("class", "btn");
	car.mileage = 0;
	car.x = 430 * car.scale;
	car.rotation = 0;
	car.score = 100;
	car.isLose = false;
	car.showKM = false;
	car.kmAlpha = 0;
	car.start = false;
	car.addedLocal = false;
	car.chaos = false;
	car.chaosRotation = 0;
	car.startClicked = false;
	car.flash = false;
	car.flashOn = false;
	car.carAlpha = 1;
	car.theCar.onload = function() {
		car.run();
	}
	return false;
}

// 绘制赛道与赛道上的障碍物以及发动机
car.drawRoad = function() {
	
	var _h = 900 * car.scale;

	var _roadH = 7200 * car.scale;

	var _ry = car.mileage % _roadH;

	var _offsetT = _ry - _h;

	car.ctx.clearRect(0, 0, car.width, car.height);

	if (_offsetT >= 5400 * car.scale && _offsetT <= 7200 * car.scale) {
		car.ctx.drawImage(car.road8, 0, _ry - _roadH - _h + car.height);
	}

	if (_offsetT >= -1800 * car.scale && _offsetT <= 0) {
		car.ctx.drawImage(car.road8, 0, _ry - _h + car.height);
	}

	_h += 900 * car.scale;
	_offsetT = _ry - _h;
	if (_offsetT >= -1800 * car.scale && _offsetT <= 0) {
		car.ctx.drawImage(car.road7, 0, _ry - _h + car.height);
	}

	_h += 900 * car.scale;
	_offsetT = _ry - _h;
	if (_offsetT >= -1800 * car.scale && _offsetT <= 0) {
		car.ctx.drawImage(car.road6, 0, _ry - _h + car.height);
	}

	_h += 900 * car.scale;
	_offsetT = _ry - _h;
	if (_offsetT >= -1800 * car.scale && _offsetT <= 0) {
		car.ctx.drawImage(car.road5, 0, _ry - _h + car.height);
	}

	_h += 900 * car.scale;
	_offsetT = _ry - _h;
	if (_offsetT >= -1800 * car.scale && _offsetT <= 0) {
		car.ctx.drawImage(car.road4, 0, _ry - _h + car.height);
	}

	_h += 900 * car.scale;
	_offsetT = _ry - _h;
	if (_offsetT >= -1800 * car.scale && _offsetT <= 0) {
		car.ctx.drawImage(car.road3, 0, _ry - _h + car.height);
	}

	_h += 900 * car.scale;
	_offsetT = _ry - _h;
	if (_offsetT >= -1800 * car.scale && _offsetT <= 0) {
		car.ctx.drawImage(car.road2, 0, _ry - _h + car.height);
	}

	_h += 900 * car.scale;
	_offsetT = _ry - _h;
	if (_offsetT >= -1800 * car.scale && _offsetT <= 0) {
		car.ctx.drawImage(car.road1, 0, _ry - _h + car.height);
	}

	if (car.stx) {
		if (car.somethingType == 0 || car.somethingType == 1) {
			// 小水塘
			car.ctx.save();
			car.ctx.globalAlpha = car.flyAlpha;
			car.ctx.drawImage(car.oilArr[0], car.stx - 25, (car.mileage - car.mileageOld - 50 - car.flyY));
			car.ctx.restore();

			if (car.debug) {
				car.ctx.fillStyle = "#00FF00";
				car.ctx.beginPath();
				car.ctx.arc(car.stx - 30, (car.mileage - car.mileageOld), 5, 0, Math.PI*2, true);
				car.ctx.arc(car.stx + 30, (car.mileage - car.mileageOld), 5, 0, Math.PI*2, true);
				car.ctx.closePath();
				car.ctx.fill();
			}

		} else if (car.somethingType == 2 || car.somethingType == 3) {
			// 大水塘
			car.ctx.save();
			car.ctx.globalAlpha = car.flyAlpha;
			car.ctx.drawImage(car.oilArr[1], car.stx - 33, (car.mileage - car.mileageOld - 50 - car.flyY));
			car.ctx.restore();

			if (car.debug) {
				car.ctx.fillStyle = "#00FF00";
				car.ctx.beginPath();
				car.ctx.arc(car.stx - 30, (car.mileage - car.mileageOld), 5, 0, Math.PI*2, true);
				car.ctx.arc(car.stx + 30, (car.mileage - car.mileageOld), 5, 0, Math.PI*2, true);
				car.ctx.closePath();
				car.ctx.fill();
			}

		} else {
			// 金嘉护
			car.ctx.drawImage(car.jjh[car.jjhRandom], car.stx - 30, (car.mileage - car.mileageOld - 60));

			if (car.debug) {
				car.ctx.fillStyle = "#00ff00";
				car.ctx.beginPath();
				car.ctx.arc(car.stx, (car.mileage - car.mileageOld), 30, 0, Math.PI * 2, true);
				car.ctx.closePath();
				car.ctx.fill();
			}
		}
	}

}

car.drawSomething = function() {
	car.flyAlphaBool = false;
	car.flyAlpha = 1;
	car.flyY = 0;
	car.somethingType = Math.floor(Math.random() * 5);
	var _x = (car.newCheckRoadY + 13) % car.roadX.length;
	car.stx = car.roadX[_x] * car.scale + Math.random() * 180 - 120;
	if (car.somethingType == 2 || car.somethingType == 3) {
		car.stx = car.roadX[_x] * car.scale + Math.random() * 180 - 120;
	} else {
		car.jjhRandom += 1;
		if (car.jjhRandom > 6) {
			car.jjhRandom = 0;
		}
	}
	car.oilRandom = Math.floor(Math.random() * 3);
	car.mileageOld = car.mileage + 100;
	car.hasTouch = false;
}

// 绘制车子与发动机
car.drawCar = function() {
	car.ctx.save();
	if (car.chaos) {
		car.chaosRotation += car.chaosRandom;
	} else {
		car.chaosRotation = car.chaosRotation / 1.03;
	}
	car.x += (car.rotation + car.chaosRotation) / (40 / car.currentSpeed) * car.scale;
	car.ctx.translate(car.x, car.height - 60);
	car.ctx.rotate((car.rotation + car.chaosRotation) * Math.PI / 180);
	
	if (car.flash) {
		if (car.flashOn) {
			car.carAlpha += 0.07;
		} else {
			car.carAlpha -= 0.07;
		}
		if (car.carAlpha > 1) {
			car.flashOn = false;
			car.carAlpha = 1;
		} else if (car.carAlpha < 0) {
			car.flashOn = true;
			car.carAlpha = 0;
		}
		car.ctx.globalAlpha = car.carAlpha;
	}

	if (Math.abs(car.rotation + car.chaosRotation) > 15 || car.x > car.roadCenter + (car.roadWidth / 2 + 10) || car.x < car.roadCenter - (car.roadWidth / 2 + 10) || car.chaos) {
		car.ctx.drawImage(car.theCarShadow, -car.theCarShadow.width / 2 + 1, 20 + Math.random() * 5);
	}

	car.ctx.drawImage(car.theCar, -car.theCar.width / 2, -car.theCar.height / 2 - 20);
	
	if (car.whosyourdaddy) {
		if (car.lightOn) {
			car.lightAlpha += 0.05;
		} else {
			car.lightAlpha -= 0.05;
		}
		if (car.lightAlpha > 1) {
			car.lightOn = false;
			car.lightAlpha = 1;
		} else if (car.lightAlpha < 0) {
			car.lightOn = true;
			car.lightAlpha = 0;
		}
		car.ctx.globalAlpha = car.lightAlpha;
		car.ctx.drawImage(car.light, -car.theCar.width / 2, -car.theCar.height / 2 - 20);
	}

	

	car.ctx.restore();

	car.ctx.drawImage(car.hpbg, car.hpX, 80);
	var _y = 252 * (car.score / 100) + 8;
	if (_y != 8 * car.scale) {
		car.ctx.drawImage(car.hp, 0, 261, 18, 8, car.hpX, 340, 18, 8);
		car.ctx.drawImage(car.hp, 0, _y, 18, -_y, car.hpX, 340, 18, -_y);
	}

	car.ctx.restore();

	if (car.debug) {
		car.ctx.fillStyle = "#00FF00";
		car.ctx.beginPath();
		car.ctx.arc(car.x, car.height - 60, 5, 0, Math.PI * 2, true);
		car.ctx.closePath();
		car.ctx.fill();
	}
}

// 绘制云
car.drawCloud = function() {
	return false;
	car.ctx2.save();

	if (car.cloudX == null) {
		car.cloudX = 0;
	}
	car.cloudX += 1;
	if (car.cloudX > 900) {
		car.cloudX = -900;
	}

	var _h = 900;

	var _roadH = 3600;

	var _ry = car.mileage % _roadH;

	var _offsetT = _ry - _h;

	car.ctx2.clearRect(0, 0, car.width, car.height);

	if (_offsetT >= 1800 && _offsetT <= 3600) {
		car.ctx2.drawImage(car.cloud[0], car.cloudX, _ry - _roadH - _h + car.height);
		if (car.cloudX < 0) {
			car.ctx2.drawImage(car.cloud[0], car.cloudX + 900, _ry - _roadH - _h + car.height);
		} else {
			car.ctx2.drawImage(car.cloud[0], car.cloudX - 900, _ry - _roadH - _h + car.height);
		}
	}

	if (_offsetT >= -1800 && _offsetT <= 0) {
		car.ctx2.drawImage(car.cloud[0], car.cloudX, _ry - _h + car.height);
		if (car.cloudX < 0) {
			car.ctx2.drawImage(car.cloud[0], car.cloudX + 900, _ry - _h + car.height);
		} else {
			car.ctx2.drawImage(car.cloud[0], car.cloudX - 900, _ry - _h + car.height);
		}
	}

	_h += 900;
	_offsetT = _ry - _h;
	if (_offsetT >= -1800 && _offsetT <= 0) {
		car.ctx2.drawImage(car.cloud[1], car.cloudX, _ry - _h + car.height);
		if (car.cloudX < 0) {
			car.ctx2.drawImage(car.cloud[1], car.cloudX + 900, _ry - _h + car.height);
		} else {
			car.ctx2.drawImage(car.cloud[1], car.cloudX - 900, _ry - _h + car.height);
		}
	}

	_h += 900;
	_offsetT = _ry - _h;
	if (_offsetT >= -1800 && _offsetT <= 0) {
		car.ctx2.drawImage(car.cloud[2], car.cloudX, _ry - _h + car.height);
		if (car.cloudX < 0) {
			car.ctx2.drawImage(car.cloud[2], car.cloudX + 900, _ry - _h + car.height);
		} else {
			car.ctx2.drawImage(car.cloud[2], car.cloudX - 900, _ry - _h + car.height);
		}
	}

	_h += 900;
	_offsetT = _ry - _h;
	if (_offsetT >= -1800 && _offsetT <= 0) {
		car.ctx2.drawImage(car.cloud[3], car.cloudX, _ry - _h + car.height);
		if (car.cloudX < 0) {
			car.ctx2.drawImage(car.cloud[3], car.cloudX + 900, _ry - _h + car.height);
		} else {
			car.ctx2.drawImage(car.cloud[3], car.cloudX - 900, _ry - _h + car.height);
		}
	}


	car.ctx2.restore();
}

// 开动车子
car.run = function() {
	if (car.isLose) {
		car.flash = false;
		car.drawRoad();
		car.drawCar();
		car.drawCloud();

		if (car.score <= 0) {
			car.score = 0;
		}

		// car.ctx.fillStyle="#000000";
		// car.ctx.fillRect(1024 - 150, 30, 150, 75);
	 	// car.ctx.fillStyle = '#fff';
		// car.ctx.font ="18px Times New Roman";
		// car.ctx.fillText("性能: " + Math.ceil(car.score), 1024 - 130, 60);
		// car.ctx.fillText("路程: " + Math.ceil(car.LastMileage / 10), 1024 - 130, 88);

		// if (!car.addedLocal) {
		// 	if (localStorage.score == "undefined" || localStorage.score == undefined) {
		// 		localStorage.score = "";
		// 	}
		// 	localStorage.score += Math.ceil(car.LastMileage / 10) + "||";
		// 	var _scoreArr = localStorage.score.split("||");
		// 	// if (_scoreArr[_scoreArr.length - 1] == "") {
		// 	// 	_scoreArr.pop();
		// 	// }
		// 	car.champion = _scoreArr.sort(function compare(a,b){return b-a;});
		// 	car.addedLocal = true;
		// }

		// car.ctx.fillStyle="#000000";
		// car.ctx.save();
		// car.ctx.globalAlpha = 0.3;
		// car.ctx.fillRect(0, 0, 1024, 768);
		// car.ctx.restore();
		// car.ctx.fillStyle="#000000";
		// car.ctx.fillRect((1024 - 300) / 2, 230, 300, 190);
		// car.ctx.fillStyle = '#ffd91d';
		// car.ctx.font ="24px Hiragino Sans GB";
		// car.ctx.textAlign = "center";
		// car.ctx.textBaseline = "middle";
		// car.ctx.fillText("游戏结束", 1024 / 2, 280);
		// car.ctx.font ="18px Hiragino Sans GB";
		// car.ctx.fillText("您的成绩：" + Math.ceil(car.LastMileage / 10) + "米", 1024 / 2, 330);
		// car.ctx.fillText("最高成绩：" + car.champion[0] + "米", 1024 / 2, 360);

		car.currentSpeed -= 0.5;
		car.mileage += car.currentSpeed;
		if (car.currentSpeed < 0) {
			page.bgAudio("audio/bg.mp3");
			var _num = $("#gameing>.title h6").html();
            if (_num) {
            	_num = parseInt(_num);
            	if (_num > 0) {
            		$("#beforeGame #title h6, #gameing>.title h6, #gameing>.counts").html(_num - 1);
            	}
            }
			car.targetScore = Math.ceil(car.LastMileage / 10);
			var _id = localStorage.getItem("id") || "0";
			if (_id != "0") {
				$("#gameing .blurs").addClass("blur");
				$("#gameing>.title").addClass("show");
				$("#gameing .score .sl .s1 ul").empty();
				$("#gameing .score .sl .s2 ul").empty();
				$("#gameing .score .title").html("您本次挑战得分：" + car.targetScore + "米");
				if (car.targetScore > 5000) {
					$.ajax({
				        type: "GET",
				        url: page.service + "GetShareNotice",
				        data: {"score": car.targetScore},
				        dataType: "jsonp",
				        success: function(e){
				            __SNShare = e.sina;
				            __TXShare = e.ten;
				        }
				    });
					$("#gameing .none").pageTo($("#gameing .chooseCard"), {type: "scale"});
				} else {
					$("#gameing .none").pageTo($("#gameing .score"), {type: "scale", callback: car.updateScore});
				}
			}
			car.currentSpeed = 0;
		} else {
			car.timeout = setTimeout(car.run, 1000 / 60);
		}
	} else {
		car.drawRoad();
		car.drawCar();
		car.drawCloud();

		car.showInfo();
		car.showEachKM();
		if (!car.start) {
			return false;
		}
		car.oldCheckRoadY = Math.floor(car.mileage / 50);

		if (!car.chaos && car.useSpeed != 0) {
			if (car.addSpeed) {
				car.currentSpeed += 1;
				if (car.currentSpeed > car.useSpeed * ((90 - Math.abs(car.rotation)) / 90)) {
					car.currentSpeed = car.useSpeed * ((90 - Math.abs(car.rotation)) / 90);
				}
			} else {
				car.currentSpeed += 0.2;
				if (car.currentSpeed > car.useSpeed * ((90 - Math.abs(car.rotation)) / 90) + 0.2) {
					car.currentSpeed -= 0.4;
				}
			}
		} else {
			car.currentSpeed -= 0.1;
		}


		if (car.currentSpeed < 0) {
			car.currentSpeed = 0;
		}
		car.eachkm = Math.floor(car.mileage / 10000);
		car.mileage += car.currentSpeed;
		if (car.eachkm != Math.floor(car.mileage / 10000)) {
			car.showKM = true;
			car.kmAlpha = 0;
			setTimeout(function(){
				car.showKM = false;
			}, 3000);
		}

		if (car.x < 60) {
			car.x = 60;
		} else if (car.x > car.width - 60) {
			car.x = car.width - 60;
		}

		car.newCheckRoadY = Math.floor(car.mileage / (50 * car.scale));
		if (car.oldCheckRoadY !== car.newCheckRoadY) {
			if (car.newCheckRoadY % 20 == 0) {
				var _random = Math.floor(Math.random() * 3);
				if (_random <= 1) {
					car.drawSomething();
				}
			}
			car.checkCarOnTheRoad(car.newCheckRoadY);
		}
		car.checkCarGetSomething();

		car.timeout = setTimeout(car.run, 1000 / 60);
	}
}

car.updateScore = function() {
	$.ui.loading("show", "加载中...");
	var _id = localStorage.getItem("id") || "0";
	if (_id != "0") {
	    $.ajax({
	        type: "GET",
	        url: page.service + "GameOver",
	        data: {"id": _id, "score": car.targetScore},
	        dataType: "jsonp",
	        success: function(e){
	            $.ui.loading("hide");
	            if (e.status == -1) {
	                systemNotification(e.info);
	            } else if (e.status == 1) {
	                console.log(e)
	                var _html = "";
	                var _list = e.list;
	                for (var i = 0; i < _list.length; i++) {
	                    _html += "<li><span>" + _list[i].sort + "</span><span>" + _list[i].nickname + "</span><span>" + _list[i].score + "</span></li>";
	                }
	                $("#gameing .score .sl .s1 ul").html(_html);

	                _html = "";
	                _list = e.user;
	                for (var i = 0; i < _list.length; i++) {
	                    if (_list[i].id == _id) {
	                        _html += "<li class='you'><span>" + _list[i].sort + "</span><span>玩家</span><span>" + _list[i].score + "</span></li>";
	                    } else {
	                        _html += "<li><span>" + _list[i].sort + "</span><span>" + _list[i].nickname + "</span><span>" + _list[i].score + "</span></li>";
	                    }
	                }
	                $("#gameing .score .sl .s2 ul").html(_html);
	                setTimeout(function(){
	                    page.scoreList1Scroll.refresh();
	                    page.scoreList2Scroll.refresh();
	                }, 100);
	                page.getUserCount();
	            }
	        },
	        error: function(xhr, type){
	            $.ui.loading("hide");
	        }
	    });
	}
}

// 显示里程
car.showEachKM = function() {
	if (car.showKM) {
		car.kmAlpha += 0.1;
		if (car.kmAlpha > 1) {
			car.kmAlpha = 1;
		}
	} else if (!car.showKM && car.kmAlpha > 0) {
		car.kmAlpha -= 0.1;
	} else {
		return false;
	}
	if (car.showKM || (!car.showKM && car.kmAlpha > 0)) {
		car.ctx.save();
		car.ctx.globalAlpha = car.kmAlpha;
		car.ctx.beginPath();
		// car.ctx.fillRect(367, 30, 200, 46);
		// car.ctx.fillStyle = '#ffd91d';

		car.ctx.drawImage(car.eachkmImg, 340 - 55, 30);
		car.ctx.fillStyle = "#222222";
		car.ctx.font ="18px Hiragino Sans GB";
		car.ctx.textAlign = "center";
		car.ctx.textBaseline = "middle";
		car.ctx.fillText(car.eachkm * 1000 + "米", 340, 46);
		car.ctx.closePath();
		car.ctx.fill();
		car.ctx.restore();
	}
}

// 判断车是否在车道上
car.checkCarOnTheRoad = function(y) {
	car.lake = car.dieX[y % car.dieX.length] * car.scale;

	if (car.lake != -1) {
		if (car.debug) {
			car.ctx.fillStyle = "#00FF00";
			car.ctx.beginPath();
			car.ctx.arc(car.lake, 640 * car.scale - 120 * car.scale, 15, 0, Math.PI*2, true);
			car.ctx.closePath();
			car.ctx.fill();
		}
		if ((car.lake > car.roadCenter && car.x > car.lake) || (car.lake < car.roadCenter && car.x < car.lake)) {
			car.currentSpeed = 0;
			car.x = car.roadCenter;
			car.score -= 10;
			car.chaos = false;
			car.rotation = 0;
			car.chaosRandom = 0;
			car.chaosRotation = 0;
			car.lightAlpha = 0;
			car.whosyourdaddy = false;
			car.addSpeed = false;
			car.useSpeed = 0;
			car.flash = true;
			clearTimeout(car.fastTimer);
			clearTimeout(car.daddyTimer);
			setTimeout(function(){
				car.flash = false;
				car.useSpeed = car.defaultDpeed;
			}, 1000);
		}
	}

	
	car.roadCenter = car.roadX[y % car.roadX.length] * car.scale;

	if (car.debug) {
		car.ctx.fillStyle = "#00FF00";
		car.ctx.beginPath();
		car.ctx.arc(car.roadCenter, 640 * car.scale - 120 * car.scale, 15, 0, Math.PI*2, true);
		car.ctx.closePath();
		car.ctx.fill();

		car.ctx.fillStyle = "#FF0000";
		car.ctx.beginPath();
		car.ctx.arc(car.roadCenter - car.roadWidth / 2, 640 * car.scale - 120 * car.scale, 15, 0, Math.PI*2, true);
		car.ctx.arc(car.roadCenter + car.roadWidth / 2, 640 * car.scale - 120 * car.scale, 15, 0, Math.PI*2, true);
		car.ctx.closePath();
		car.ctx.fill();
	}

	if (car.whosyourdaddy) {
		return false;
	}

	if (car.x < car.roadCenter - car.roadWidth / 2 || car.x > car.roadCenter + car.roadWidth / 2) {
		car.score -= car.currentSpeed * 0.02;
	} else {
		car.score -= car.currentSpeed * 0.0015;
	}

}

car.checkCarGetSomething = function() {
	if (!car.hasTouch && car.mileage - car.mileageOld > 150 && car.whosyourdaddy) {
		if (car.somethingType == 0 || car.somethingType == 1 || car.somethingType == 2 || car.somethingType == 3) {
			if (!car.flyAlphaBool) {
				car.flyAlphaBool = true;
				car.flyAlpha = 1;
				car.flyY = 0;
			} else {
				car.flyAlpha -= 0.1;
				car.flyY = 0;
				if (car.flyAlpha < 0) {
					car.flyAlpha = 0;
				}
			}
			if (car.x < car.stx) {
				car.stx += 20;
			} else {
				car.stx -= 20;
			}
		}
	}
	if (!car.hasTouch && car.mileage - car.mileageOld > 320) {
		if (car.somethingType == 0 || car.somethingType == 1) {
			// 小水塘
			if (car.whosyourdaddy) {
				car.chaos = false;
				return false;
			}
			if (car.x > car.stx - 30 && car.x < car.stx + 30) {
				car.score -= 3;
				console.log("score : -3");
				car.chaos = true;
				car.chaosRandom = Math.random() * 1 - 0.5;
				car.flash = true;
				clearTimeout(car.chaosTimer);
				car.chaosTimer = setTimeout(function(){
					car.chaos = false;
					car.flash = false;
				}, 1000);
				// car.ctx.fillStyle = "#ff0000";
				// car.ctx.beginPath();
				// car.ctx.arc(car.stx - 60, 600, 5, 0, Math.PI*2, true);
				// car.ctx.arc(car.stx + 60, 600, 5, 0, Math.PI*2, true);
				// car.ctx.closePath();
				// car.ctx.fill();
				// alert(1);
			}
		} else if (car.somethingType == 2 || car.somethingType == 3) {
			// 大水塘
			if (car.whosyourdaddy) {
				car.chaos = false;
				return false;
			}
			if (car.x > car.stx - 30 && car.x < car.stx + 30) {
				car.score -= 3;
				console.log("score : -3");
				car.chaos = true;
				car.chaosRandom = Math.random() * 1 - 0.5;
				car.flash = true;
				clearTimeout(car.chaosTimer);
				car.chaosTimer = setTimeout(function(){
					car.chaos = false;
					car.flash = false;
				}, 1000);
				// car.ctx.fillStyle = "#ff0000";
				// car.ctx.beginPath();
				// car.ctx.arc(car.stx - 80, 600, 5, 0, Math.PI*2, true);
				// car.ctx.arc(car.stx + 80, 600, 5, 0, Math.PI*2, true);
				// car.ctx.closePath();
				// car.ctx.fill();
				// alert(1);
			}
		} else {
			// 金嘉护
			if (car.x > car.stx - 60 && car.x < car.stx + 60) {
				
				car.whosyourdaddy = true;
				car.chaos = false;
				car.chaosRotation = 0;
				car.lightAlpha = 0;
				car.addSpeed = true;
				car.useSpeed = car.jsdSpeed;
				clearTimeout(car.fastTimer);
				clearTimeout(car.daddyTimer);
				car.fastTimer = setTimeout(function(){
					car.useSpeed = car.defaultDpeed;
					car.addSpeed = false;
					car.daddyTimer = setTimeout(function(){
						car.whosyourdaddy = false;
						car.lightAlpha = 1;
					}, 3000);
				}, 5000);

			}
		}
		console.log(car.x, car.stx);
		console.log("==========================================");
		car.hasTouch = true;
	}
}

car.showInfo = function() {
	if (car.score <= 0) {
		car.score = 0;
		car.isLose = true;
		return false;
	}
	car.LastMileage = car.mileage;
	// car.ctx.fillStyle="#000000";
	// car.ctx.fillRect(1024 - 150, 30, 150, 75);
 	// car.ctx.fillStyle = '#fff';
	// car.ctx.font ="18px Times New Roman";
	// car.ctx.fillText("性能: " + Math.ceil(car.score), 1024 - 130, 60);
	// car.ctx.fillText("路程: " + Math.ceil(car.mileage / 10), 1024 - 130, 88);
}

// 键盘控制
car.keyDown = function(e) {
	var keycode = e.which;
	if (keycode == 90) {
		if (car.rotation >= -88) {
			car.rotation -= 10;
		}
	} else if (keycode == 88) {
		if (car.rotation <= 88) {
			car.rotation += 10;
		}
	}
}

// 根据3D陀螺仪进行操作
car.devicemotionHandler = function(e){
	if (!car.isLose && car.start) {
	    var device = parseInt(e.beta) / 5;
	    if (device > 0) {
	    	if (car.rotation <= 90 - device) {
		    	car.rotation += device;
		    }
	    } else {
	    	if (car.rotation >= -device - 90) {
		    	car.rotation += device;
		    }
	    }
    }
}

document.addEventListener(__type1, function() {
    $(function(){
    	car.init();
    });
});